import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/sub/SessionGroupSettingPage.dart';
import 'package:im_app/im/page/sub/SessionUserSettingPage.dart';
import 'package:im_app/im/page/view/ListSeparator.dart';
import 'package:im_app/im/page/view/component/SessionIconView.dart';
import 'package:im_app/im/util/DbUtil.dart';
import 'package:im_app/im/util/ImConstant.dart';
import 'package:im_app/im/util/UiUtil.dart';

import '../../dao/ImGroupUserDao.dart';
import '../../pojo/ImPojo.dart';
import '../../socket/dto/business/SendData.dart';
import '../../socket/service/RpcSendDataService.dart';
import '../bloc/SessionListCubit.dart';
import '../bloc/SessionSettingCubit.dart';

/// 修改群用戶名稱
class GroupChangeUserNamePage extends StatefulWidget {
  final ImSession session;

  const GroupChangeUserNamePage({required this.session, super.key});

  @override
  State<StatefulWidget> createState() => _ChangeGroupNameState();
}

class _ChangeGroupNameState extends State<GroupChangeUserNamePage> {
  var _userName = '';
  late TextEditingController _editingController;

  @override
  void initState() {
    super.initState();

    _editingController = TextEditingController();
    var userName = widget.session.group?.currentGroupUser?.userName??(widget.session.group?.currentGroupUser?.user?.userName??'');
    _editingController.text = userName;
    setState(() {
      _userName = userName;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      backgroundColor: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
      body: _buildBody(context),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      toolbarHeight: ImConstant.IM_APP_BAR_HEIGTH,
      backgroundColor: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
      leading: GestureDetector(
        child: const Icon(Icons.chevron_left),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  Widget _buildBody(BuildContext context) {
    return Center(
      child: Container(
        height: 500,
        margin: const EdgeInsets.only(left: 10, right: 10),
        child: Column(
          children: [
            const Text(
              "我在群里的昵称",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
            ),
            const Padding(
              padding: EdgeInsets.only(top: 10, bottom: 20),
              child: Text("昵称修改后，只会在此群内显示，群内成员都能看见。"),
            ),
            ListSeparator(
              indent: 20,
              endIndent: 20,
            ),
            Row(
              children: [
                Padding(padding: const EdgeInsets.only(right: 10), child: SessionIconView(session: widget.session),),
                Expanded(
                  child: TextField(
                    controller: _editingController,
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      hintText: '请输入内容',
                    ),
                    onChanged: (value) => this._userName = value,
                  ),
                ),
                Visibility(
                  replacement: const SizedBox(
                    width: 18.0,
                  ),
                  visible: _userName != '',
                  child: IconButton(
                    icon: const Icon(Icons.cancel),
                    color: Colors.grey,
                    hoverColor: Colors.white,
                    iconSize: 18.0,
                    onPressed: () {
                      _editingController.clear();
                      _userName = '';
                    },
                  ),
                )
              ],
            ),
            ListSeparator(
              indent: 20,
              endIndent: 20,
            ),
            const SizedBox(
              height: 200,
            ),
            SizedBox(width: 120, child: FilledButton(
                style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.green)),
                onPressed: _submit,
                child: const Text('完成', style: TextStyle(color: Colors.white))
            ),),
          ],
        ),
      ),
    );
  }

  void _submit() async {
    if (_userName != '') {
      if (_userName.length > ImConstant.IM_USER_NAME_LENGTH) {
        showModalBottomSheet(
            context: context,
            builder: (context) {
              return const Text('用户名太长，不能超过${ImConstant.IM_USER_NAME_LENGTH}字');
            });
        return;
      }

      var imSession = widget.session;
      ImGroup imGroup = imSession.group!;
      ImGroupUser imGroupUser = imGroup.currentGroupUser!;
      imGroupUser.userName = _userName;
      imGroupUser.updateTime = DateTime.now();

      RpcMessageService rpcMessageService = RpcMessageService();
      var key = imGroup.code + ImConstant.MESSAGE_SPLIT + imGroupUser.userId;
      DataChangeReq dataChangeReq = DataChangeReq(type: DataType.groupUser, subType: DataSubType.gu_ed_userName,
          key: key, value: _userName);
      rpcMessageService.sendDataChange(dataChangeReq);

      var imGroupUserDao = ImGroupUserDao();
      imGroupUserDao.batchUpdates([imGroupUser].toSet());

      UiUtil.uiChangeSession(imSession);

      var sessionListCubit = context.read<SessionListCubit>();
      Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) {
        return BlocProvider(
          create: (context) => SessionSettingCubit(session: widget.session, sessionListCubit: sessionListCubit),
          child: _buildSettingPage(widget.session),
        );
      }), ModalRoute.withName("/MessageSendPage"));
    } else {
      showModalBottomSheet(
          context: context,
          builder: (context) {
            return const Text('用戶名不能为空');
          });
    }
  }

  Widget _buildSettingPage(ImSession session) {
    if (session!.groupCode == null) {
      return SessionUserSettingPage();
    }
    return SessionGroupSettingPage();
  }
}
